<template>
  <div class="app-container">
    <div class="card-box">
      <span>调拨编号:</span>
      <el-select v-model="allocationNo" style="margin-left: 20px">
        <el-option
            v-for="item in allocationPlans"
            :key="item.allocationNo"
            :label="item.allocationNo"
            :value="item.allocationNo"
        />
      </el-select>
      <el-button style="margin-left: 20px" type="primary" @click="handleAllocationChange">查询</el-button>
    </div>

    <el-row>
      <el-col :span="24" class="card-box">
        <el-card>
          <el-descriptions title="基本信息" size="large">
            <el-descriptions-item label="订单编号:">
              <span style="width: 300px">{{parseTime(allocationPlan.allocationDate,"{y}-{m}-{d}")}}</span>
            </el-descriptions-item>
            <el-descriptions-item label="配送状态:">
              <el-tag size="large">{{deliveryStatusMap[deliveryStatus]}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发货日期:">
              {{ parseTime(allocationPlan.allocationDate,"{y}-{m}-{d}") }}
            </el-descriptions-item>
            <el-descriptions-item label="运输总重量:">
              {{allocationPlan.weight}}{{allocationPlan.weightUnit}}
            </el-descriptions-item>
            <el-descriptions-item label="运输总体积:">
              {{allocationPlan.volume}}{{allocationPlan.volumeUnit}}
            </el-descriptions-item>
            <el-descriptions-item label="预期到货时间:">
              {{parseTime(allocationPlan.expectedDeliveryTime,"{y}-{m}-{d}")}}
            </el-descriptions-item>
            <el-descriptions-item label="物流商名称:">
              {{allocationPlan.deliveryName}}
            </el-descriptions-item>
            <el-descriptions-item label="运送仓库:">
              {{allocationPlan.warehouseNo}}
            </el-descriptions-item>
            <el-descriptions-item label="备注:">{{allocationPlan.remarks}}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card>
          <template #header>
            <Bell style="width: 1em; height: 1em; vertical-align: middle;" />
            <span style="vertical-align: middle; margin-left: 5px">配送状态</span>
          </template>
          <el-steps style="width: 100%"
                    :active="deliveryStatus"
                    finish-status="success"
                    align-center>
            <el-step class="step" title="待生成运输订单" />
            <el-step class="step" title="待物流商确认"/>
            <el-step class="step" title="待确认"/>
            <el-step class="step" title="待配送"/>
            <el-step class="step" title="运输中" />
            <el-step class="step" title="已送达" />
          </el-steps>
        </el-card>
      </el-col>

      <el-col :span="10" class="card-box">
        <el-card style="height: 537px;">
          <template #header>
            <Message style="width: 1em; height: 1em; vertical-align: middle;" />
            <span style="vertical-align: middle; margin-left: 5px">物流信息</span>
          </template>
          <el-scrollbar max-height="457px">
            <el-timeline>
              <el-timeline-item
                  v-for="(item, index) in logisticInfo"
                  :key="index"
                  :timestamp="parseTime(item.timeStamp, '{y}-{m}-{d} {h}:{i}:{s}')"
                  :type="index === 0 ? 'primary' : 'info'"
                  size="large"
              >
                <div>
                  <div><strong>{{ item.location }}</strong></div>
                  <div>{{ item.remarks }}</div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :span="14" class="card-box">
        <el-card>
          <div id="container" style="position: relative; height: 500px; width: 100%"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ElStep, ElSteps} from "element-plus";
import {Message} from "@element-plus/icons-vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import {getAllocationPlan, getAllocationPlanByOrderNo} from "@/api/purchase/AllocationPlan.js";
import {listTransport} from "@/api/delivery/transport.js";
import {parseTime} from "@/utils/ruoyi.js";
import {getDeliveryIdByTrackingNo, getLogisticsHistory} from "@/api/delivery/delivery.js";
import {getPurchaseOrder} from "@/api/purchase/purchaseOrder.js";

const {proxy} = getCurrentInstance();

let map = null;
const allocationNo = ref('');
const deliveryId = ref('');
const allocationPlan = ref({});
const trackingNo =  ref('');
const transportOrder = ref({});
const deliveryStatus = ref(0);
const allocationPlans = ref([]);
const logisticInfo = ref([]);
const orderInfo = ref({});
const currentPosition = ref([]);

const warehouseInfo = ref({
  latitude: 37.4348,
  longitude: 122.1954
})
const deliveryStatusMap = {
  0: '待生成运输订单',
  1: '待物流商确认',
  2: '待确认',
  3: '待配送',
  4: '运输中',
  5: '已送达'
}

function initial(){
  if(proxy.$route.query.allocationNo) {
    allocationNo.value = proxy.$route.query.allocationNo;
    getAllocationPlan(allocationNo.value).then(response => {
      allocationPlan.value = response.data;
      //获取订单所有的调拨计划
      getAllocationPlanByOrderNo(allocationPlan.value.orderNo).then(response => {
        allocationPlans.value = response.data;
      })
      //获取订单详情
      getPurchaseOrder(allocationPlan.value.orderNo).then(response => {
        orderInfo.value = response.data;
      })
      //获取运单号和运输订单状态
      if(allocationPlan.value.trackingNo !== null){
        trackingNo.value = allocationPlan.value.trackingNo;
        let query = {
          trackingNumber:trackingNo.value
        }
        listTransport(query).then(response => {
          transportOrder.value = response.data[0];
          deliveryStatus.value = transportOrder.value.state + 1;
        })
        getDeliveryIdByTrackingNo(trackingNo.value).then(response => {
          deliveryId.value = response;
          getLogisticsHistory(deliveryId.value).then(response => {
            logisticInfo.value = response;
          })
        })
      }
      else{
        deliveryStatus.value = 0;
        logisticInfo.value = [];
      }
    })
    showDeliveryMap();
  }
}

function showDeliveryMap(){
  window._AMapSecurityConfig = {
    securityJsCode: "4cb512290cb2f2cde33ae3284c6b8073",
  };
  AMapLoader.load({
    key: "48dff654e078158ff016c701f2755ddf",
    version: "2.0",
    plugins: ["AMap.Scale","AMap.Driving","AMap.HawkEye"],
  })
      .then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 5, // 初始化地图级别
          center: [116.397428, 39.90923],
        });
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.HawkEye());

        let driving = new AMap.Driving({
          map: map,
          showTraffic: false,
        });

        setTimeout(() => {
          let wayPoints = [];
          logisticInfo.value.forEach((item,index) => {
            wayPoints.push(new AMap.LngLat(item.longitude, item.latitude))
          })

          let startPoint = new AMap.LngLat(orderInfo.value.destinationLng,orderInfo.value.destinationLat);
          let endPoint = new AMap.LngLat(warehouseInfo.value.longitude,warehouseInfo.value.latitude);

          driving.search(startPoint, endPoint, {waypoints:wayPoints})
        },500)

        const carIcon = new AMap.Icon({
          image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/car.png",
          size: new AMap.Size(21, 30),
          imageSize: new AMap.Size(21, 30)
        });

        setTimeout(() => {
          if(logisticInfo.value.length > 0){
            let length = logisticInfo.value.length - 1;
            currentPosition.value = new AMap.LngLat(logisticInfo.value[length].longitude,logisticInfo.value[length].latitude)
            const carMarker = new AMap.Marker({
              position: currentPosition.value,
              icon: carIcon,
              offset: new AMap.Pixel(-10, -28),
            });
            carMarker.on('click',()=>{
              openCarInfo();
            })
            map.add(carMarker);
            map.setCenter(currentPosition)
            openCarInfo();
          }
        },1500)

      })
      .catch((e) => {
        console.log(e);
      });
}

/** 调拨计划切换 */
function handleAllocationChange(){
  proxy.$router.push({
    path:'/DeliveryDetail',
    query:{
      allocationNo: allocationNo.value,
    }
  });
  setTimeout(() => {
    initial();
  },500);
}

/** 展示信息卡片 **/
function openCarInfo(){
  const content = computed(() => [
    `<div style="font-size: small"><b>${deliveryStatusMap[deliveryStatus.value]}</b>`,
    `当前位置:经(${currentPosition.value.lng})/ 纬(${currentPosition.value.lat})`,
    `预计到达时间:${parseTime(allocationPlan.value.expectedDeliveryTime,"{y}-{m}-{d}")}</div>`
  ]);
  const infoWindow = new AMap.InfoWindow({
    content: content.value.join('<br>'),
    anchor: 'top-left',
  });
  infoWindow.open(map, [currentPosition.value.lng, currentPosition.value.lat]);
}

initial();
</script>

<style scoped lang="scss">

</style>